export default function useSubtitle(props) {
  const PRINT_SPEED = 150; // 文字打印速度
  const shakeWord = ref("");

  let timer = null;

  // 开始按字渲染
  const startMove = () => {
    let s = 0;
    const total = 20;
    timer = setInterval(() => {
      const str = shakeWord.value + props.data[s];
      if (str.length > total) shakeWord.value = str.substring(1);
      else shakeWord.value = str;
      if (s >= props.data.length - 1) {
        clearMove();
      } else {
        s++;
      }
    }, PRINT_SPEED);
  };

  const clearMove = () => {
    clearInterval(timer);
  };

  watch(
    () => props.data,
    (v) => {
      shakeWord.value = "";
      if (v) {
        clearMove();
        startMove();
      }
    },
    { immediate: true }
  );

  onBeforeUnmount(() => {
    clearMove();
  });
  return {
    shakeWord,
  };
}
